/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.insurance.domain.InsuranceScheme;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.insurance.repository.InsuranceSchemeRepository;
import me.zhengjie.modules.insurance.service.InsuranceSchemeService;
import me.zhengjie.modules.insurance.service.dto.InsuranceSchemeDto;
import me.zhengjie.modules.insurance.service.dto.InsuranceSchemeQueryCriteria;
import me.zhengjie.modules.insurance.service.mapstruct.InsuranceSchemeMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author Hehh
* @date 2021-12-24
**/
@Service
@RequiredArgsConstructor
public class InsuranceSchemeServiceImpl implements InsuranceSchemeService {

    private final InsuranceSchemeRepository insuranceSchemeRepository;
    private final InsuranceSchemeMapper insuranceSchemeMapper;
    private final UserService userService;

    @Override
    public Map<String,Object> queryAll(InsuranceSchemeQueryCriteria criteria, Pageable pageable){
        Page<InsuranceScheme> page = insuranceSchemeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        if (CollUtil.isNotEmpty(page.getContent())) {
            List<Long> userIds = page.getContent().stream().map(InsuranceScheme::getCreateUserId).distinct().collect(Collectors.toList());
            Map<Long, String> userName = userService.getUserName(userIds);
            page.getContent().forEach(c -> {
                c.setCreateUserName(userName.get(c.getCreateUserId()));
            });
        }
        return PageUtil.toPage(page.map(insuranceSchemeMapper::toDto));
    }

    @Override
    public List<InsuranceSchemeDto> queryAll(InsuranceSchemeQueryCriteria criteria){
        return insuranceSchemeMapper.toDto(insuranceSchemeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public InsuranceSchemeDto findById(Long id) {
        InsuranceScheme insuranceScheme = insuranceSchemeRepository.findById(id).orElseGet(InsuranceScheme::new);
        ValidationUtil.isNull(insuranceScheme.getId(),"InsuranceScheme","id",id);
        return insuranceSchemeMapper.toDto(insuranceScheme);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public InsuranceSchemeDto create(InsuranceScheme resources) {
        boolean exists = insuranceSchemeRepository.existsBySchemeNoAndIsDeleted(resources.getSchemeNo(), 0);
        if (exists) {
            throw new BadRequestException("方案号已存在");
        }
        final Long currentUserId = SecurityUtils.getCurrentUserId();
        resources.setCreateUserId(currentUserId);
        resources.setOwnerId(currentUserId);
        resources.setIsDeleted(0);
        resources.setCreateTime(new Timestamp(System.currentTimeMillis()));
        return insuranceSchemeMapper.toDto(insuranceSchemeRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(InsuranceScheme resources) {
        InsuranceScheme insuranceScheme = insuranceSchemeRepository.findById(resources.getId()).orElseGet(InsuranceScheme::new);
        ValidationUtil.isNull( insuranceScheme.getId(),"InsuranceScheme","id",resources.getId());
        insuranceScheme.copy(resources);
        insuranceSchemeRepository.save(insuranceScheme);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            insuranceSchemeRepository.deleteById(id);
        }
    }

    /**
     * 得到名字
     *
     * @param ids id
     * @return {@link Map}<{@link Long}, {@link String}>
     */
    @Override
    public Map<Long, String> getNames(List<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyMap();
        }
        List<InsuranceScheme> schemes = insuranceSchemeRepository.findAllByIdIn(ids);
        if (CollUtil.isEmpty(schemes)) {
            return Collections.emptyMap();
        }
        return schemes.stream().collect(Collectors.toMap(InsuranceScheme::getId, InsuranceScheme::getSchemeNo));
    }

    @Override
    public void download(List<InsuranceSchemeDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (InsuranceSchemeDto insuranceScheme : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("创建人", insuranceScheme.getCreateUserId());
            map.put("是否删除", insuranceScheme.getIsDeleted());
            map.put("创建日期", insuranceScheme.getCreateTime());
            map.put("方案编号", insuranceScheme.getSchemeNo());
            map.put("保险方案0主险,1附加险", insuranceScheme.getInsuranceType());
            map.put("文件名称", insuranceScheme.getFileName());
            map.put("访问地址", insuranceScheme.getAccessUrl());
            map.put("所属人ID", insuranceScheme.getOwnerId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}